package com.rapida.net;

import java.io.UnsupportedEncodingException;

/**
 * Created by mm on 2015/1/7.
 */
public class UDPProtocol {
	private static final byte HEAD = (byte) 0xfa;
	private static final byte END = (byte) 0xab;

	public static final byte SUCCESS = (byte) 0xe1;
	public static final byte FAIL = (byte) 0xe0;

	// 询问在线主机
	public static final byte MSG_HOST_REQUEST = (byte) 0xa1;
	// 反馈主机信息
	public static final byte MSG_HOST_RESPONSE = (byte) 0xb0;
	// 通知撤销主机
	public static final byte MSG_HOST_QUIT= (byte) 0xa0;

	// 数据编码
	public static byte[] encode(byte requestType, byte[] requestData) {
		int len = 4;  //head type length end
		byte dataLen = 0;
		if (requestData != null) {
			len = 4 + requestData.length;
			dataLen = (byte) requestData.length;
		}

		byte[] r = new byte[len];
		r[0] = HEAD;
		r[len - 1] = END;
		r[1] = requestType;
		r[2] = dataLen;
		if (requestData != null) {
			System.arraycopy(requestData, 0, r, 3, requestData.length);
		}
		return r;
	}

	// 数据解码
	public static byte[] decode(byte[] data) {
		if (data[0] == HEAD && data[data.length - 1] == END) {
			int len = data[2] & 0xff;
			len = len + 1;
			byte[] r = new byte[len];
			r[0] = data[1];
			System.arraycopy(data, 3, r, 1, len - 1);
			return r;
		}
		return null;
	}

	// 封装询问在线主机消息
	public static byte[] requestHost() {
		return encode(MSG_HOST_REQUEST, null);
	}

	// 封装回复主机消息
	public static byte[] responseHost(Host host) {
		try {
			return encode(MSG_HOST_RESPONSE, host.getName().getBytes("utf-8"));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return null;
	}
}
